﻿//-----------------------------------------------------------------------------
// <copyright file="SimpleViewModelActivator.cs" company="William E. Kempf">
//     Copyright (c) William E. Kempf.
// </copyright>
//-----------------------------------------------------------------------------

namespace Onyx.Windows
{
    using System;
    using System.Reflection;

    /// <summary>
    /// Provides a simple default view model activator implementation.
    /// </summary>
    internal class SimpleViewModelActivator : IViewModelActivator
    {
        /// <summary>
        /// Creates the view model.
        /// </summary>
        /// <param name="viewModelType">Type of the view model.</param>
        /// <param name="view">The <see cref="View"/> to associate with the view model.</param>
        /// <returns>
        /// A new instance of <paramref name="viewModelType"/>.
        /// </returns>
        public object CreateViewModel(Type viewModelType, View view)
        {
            ConstructorInfo ctor = viewModelType.GetConstructor(new Type[] { typeof(View) });
            if (ctor != null)
            {
                return ctor.Invoke(new object[] { view });
            }

            ctor = viewModelType.GetConstructor(new Type[] { view.ViewElement.GetType() });
            if (ctor != null)
            {
                return ctor.Invoke(new object[] { view.ViewElement });
            }

            ctor = viewModelType.GetConstructor(Type.EmptyTypes);
            if (ctor != null)
            {
                return ctor.Invoke(null);
            }

            return null;
        }
    }
}
